package com.foreknow.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定义前端控制器 拦截url 格式要求： /控制器类名/控制器方法名
 *  http://localhost:8080/elm/Controller类名/Controller方法名
 */
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器端向客户端响应的内容的类型(MIME) https://www.runoob.com/http/mime-types.html
        resp.setContentType("text/html;charset=utf-8");
        //设置请求的字符编码集
        req.setCharacterEncoding("utf-8");
        //获取到前台发送给后台的url路径 /Controller类名/Controller方法名
        String path = req.getServletPath();
        //从以上获取到的字符串中截取Controller类名和Controller方法名
        String className = path.substring(1,path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/") + 1);
        PrintWriter out = resp.getWriter();
        //需要使用Java中的反射机制动态调用Controller中的方法
        try {
            //1. 获取 Class 对象
            Class clazz = Class.forName("com.foreknow.elm.controller." + className);
            //2. 创建对象
            Object controller = clazz.newInstance();
            //3. 获取类中的方法 methodName表示方法名  HttpServletRequest.class 表示方法的参数
            Method method = clazz.getMethod(methodName,HttpServletRequest.class);
            //4. 调用Controller对象中的方法并返回结果
            Object result = method.invoke(controller,req);
            //5. 要将result以json的数据格式（字符串）返回给前端(可以使用jackson转换工具)
            ObjectMapper objectMapper = new ObjectMapper();
            out.println(objectMapper.writeValueAsString(result));


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}
